
import subprocess
import time
import re
from datetime import datetime
from collections import defaultdict

count = 0
load = 0
cpu_rate = 0
mem_rate = 0
utilper = 0
cpu_rate_regex = " (?P<value>[0-9.]+) \\x1b\(B\\x1b\[m\\x1b\[39;49mid"
load_regex = "load average: (?P<value>[0-9.]+), "
mem_total_regex = " (?P<value>[0-9.]+) \\x1b\(B\\x1b\[m\\x1b\[39;49mtotal"
mem_used_regex = " (?P<value>[0-9.]+) \\x1b\(B\\x1b\[m\\x1b\[39;49mused"
utilper_regex = "sda[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)[ ]+([0-9.]+)\n"
util_collector = defaultdict(int)
rkbs = 0
wkbs = 0

while True:
    p = subprocess.Popen("top -n 1", shell=True, stdout=subprocess.PIPE)
    out = p.stdout.readlines()
    
    # 获取负载、CPU使用率、内存使用率指标
    load += float(re.search(load_regex, out[0].decode("utf-8")).group('value')) if count > 12 else 0
    cpu_rate += float(re.search(cpu_rate_regex, out[2].decode("utf-8")).group('value'))
    mem_total = float(re.search(mem_total_regex, out[3].decode("utf-8")).group('value'))
    mem_used = float(re.search(mem_used_regex, out[3].decode("utf-8")).group('value'))
    mem_rate += round(mem_used/mem_total, 2)
    
    
    # 获取磁盘IO指标
    p = subprocess.Popen("iostat -x 1 5", shell=True, stdout=subprocess.PIPE)
    out = p.stdout.read()
    res = re.findall(utilper_regex, out.decode("utf-8"))
    for row in res:
        rkbs += float(row[4])
        wkbs += float(row[5])
        util_collector[int(float(row[-1]))//10] += 1
    
    # 计算均值/分布
    count += 1
    avg_load = round(load/(count-12), 2) if count > 12 else 0
    avg_cpu_rate = round(100-cpu_rate/count, 2)
    avg_mem_rate = round(mem_rate/count, 2)
    avg_rkbs = round(rkbs/count/10, 2)
    avg_wkbs = round(wkbs/count/10, 2)
    
    print("{}   -   {}  {}  {}  {}  {} {}".format(datetime.now(), avg_load, avg_cpu_rate, avg_mem_rate, avg_rkbs, avg_wkbs, util_collector))